﻿var MappingModel = new function () {
    this.DisplaySecondView = ko.observable(false);
    this.TotalHeaders = ko.observable(40);
    this.HeaderText = ko.observable("cột được map");
    this.TotalMatchedHeaders = ko.observable(17);
    this.ProgressValue = ko.observable('0%');
    this.CheckProgressValue = ko.computed(function () {
        this.ProgressValue((100 * this.TotalMatchedHeaders() / this.TotalHeaders()) + '%');
    }, this);
    this.MappingColumns = ko.observableArray();

    this.AllFieldGroups = ko.observableArray();
    this.DisplayedColumns = ko.observableArray();
    this.DisplayedGroups = ko.observableArray();
    this.CurrentFieldGroups = ko.observableArray();
    this.CurrentFieldsInOrder = ko.observableArray();

    // All, Unmatched
    // None knockout properties
    this.ViewType = "All";
    this.ActiveColumn = null;
    this.LastMappedColumns = "";
    this.Initialized = false;

    this.SearchFieldText = ko.observable("Tìm tên cột");
    this.FilterMode = ko.observable("DataType"); // DataType, All
    this.AllColumnsMapped = ko.observable(false);

    this.EnableSearch = ko.computed(function () {
        return (this.DisplayedGroups().length > 0 || (this.TotalHeaders() - this.TotalMatchedHeaders()) > 0);
    }, this);

    this.UpdateView = function () {
        var unmappedCount = 0;
        this.Initialized = true;
        var firstUnmappedColumnName = "";
        this.DisplayedColumns.removeAll();
        this.DisplayedGroups.removeAll();
        $(".i-matched").remove();
        $(".i-matched1").remove();
        var foundFirstItem = false;

        if (this.ViewType == "All") {
            // Lookup on each columns
            // Filters
            for (var i = 0; i < this.MappingColumns().length; i++) {
                var item = this.MappingColumns()[i];
                if (item.IsIgnored == false) {
                    if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                        unmappedCount = unmappedCount + 1;
                    }
                    var newItem = {
                        ColumnName: item.ColumnName,
                        IsIgnored: item.IsIgnored,
                        PossibleGroups: item.PossibleGroups,
                        PossibleFieldsInOrder: item.PossibleFieldsInOrder,
                        MappedField: item.MappedField,
                        IsActive: false
                    };
                    if (item.MappedField == null && foundFirstItem == false && item.IsIgnored != true) {
                        firstUnmappedColumnName = item.ColumnName;
                        foundFirstItem = true;
                        newItem.IsActive = true;
                        this.ActiveColumn = newItem;
                    }
                    // Show log
                    this.DisplayedColumns.push(newItem);
                }
            }

            // Set active column
            if (!foundFirstItem) {
                this.ActiveColumn = null;
                this.AllColumnsMapped(true);
            }
        }
        else {
            for (var i = 0; i < this.MappingColumns().length; i++) {
                var item = this.MappingColumns()[i];
                if (item.IsIgnored == false) {
                    if (typeof (item.MappedField) == "undefined" || item.MappedField == null) {
                        unmappedCount = unmappedCount + 1;
                        var newItem = {
                            ColumnName: item.ColumnName,
                            IsIgnored: item.IsIgnored,
                            PossibleGroups: item.PossibleGroups,
                            PossibleFieldsInOrder: item.PossibleFieldsInOrder,
                            MappedField: item.MappedField,
                            IsActive: false
                        };
                        if (!foundFirstItem) {
                            newItem.IsActive = true;
                            firstUnmappedColumnName = item.ColumnName;
                            foundFirstItem = true;
                            newItem.IsActive = true;
                            this.ActiveColumn = newItem;
                        }

                        // Show log
                        // console.log(item);
                        this.DisplayedColumns.push(newItem);
                    }
                }
            }
            if (!foundFirstItem) {
                this.ActiveColumn = null;
                this.AllColumnsMapped(true);
            }
        }
        if (this.ActiveColumn == null) {
            MappingModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
            document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-blue right");
            return;
        }
        else {
            document.getElementById("NextToStep3").setAttribute("class", "btn btn-next-gray right");
        }
        if ((this.FilterMode() == "DataType") && ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Tìm tên cột"))) {
            this.CurrentFieldGroups(clone(this.ActiveColumn.PossibleGroups));
            this.CurrentFieldsInOrder(clone(this.ActiveColumn.PossibleFieldsInOrder));
        }
        else {
            this.CurrentFieldGroups(clone(this.AllFieldGroups()));
        }

        // All columns headers matched
        MappingModel.TotalMatchedHeaders(this.MappingColumns().length - unmappedCount);
        this.FilterFieldGroups();

        // Set all groups
        this.DisplayedGroups(this.CurrentFieldGroups());
        if (this.ActiveColumn != "undefined" && this.ActiveColumn != null)
            document.getElementById(this.ActiveColumn.ColumnName).scrollIntoView(true);
    };

    this.FilterFieldGroups = function () {
        if ((this.FilterMode() == "DataType") && ((this.SearchFieldText() == "") || (this.SearchFieldText() == "Tìm tên cột"))) {
            for (var i = this.CurrentFieldsInOrder().length - 1; i > -1; i--) {
                if (this.CurrentFieldsInOrder()[i].IsUsed == "true") {
                    this.CurrentFieldsInOrder().splice(i, 1);
                }
            }

            if (this.CurrentFieldsInOrder().length > 10) {
                this.CurrentFieldsInOrder().splice(10, this.CurrentFieldsInOrder().length - 10);
            }

            for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
                var groupItem = this.CurrentFieldGroups()[i];
                var groupHasChildren = false;
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var j = groupItem.Fields.length - 1; j > -1; j--) {
                        var fieldItem = groupItem.Fields[j];

                        if (fieldItem.IsUsed == true) {
                            groupItem.Fields.splice(j, 1);
                        }
                        else {
                            var found = false;
                            for (var k = 0; k < this.CurrentFieldsInOrder().length; k++) {
                                var orderedFI = this.CurrentFieldsInOrder()[k];
                                if (fieldItem.FieldId == orderedFI.FieldId) {
                                    found = true;
                                    break;
                                }
                            }
                            if (found == false) {
                                groupItem.Fields.splice(j, 1);
                            }
                        }
                    }

                    if (groupItem.Fields.length > 0) {
                        groupHasChildren = true;
                    }
                }

                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var j = groupItem.Sections.length - 1; j > -1; j--) {
                        var sectionItem = groupItem.Sections[j];
                        for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
                            var fieldItem = sectionItem.Fields[k];

                            if (fieldItem.IsUsed == true) {
                                sectionItem.Fields.splice(k, 1);
                            }
                            else {
                                var found = false;
                                for (var l = 0; l < this.CurrentFieldsInOrder().length; l++) {
                                    var orderedFI = this.CurrentFieldsInOrder()[l];
                                    if (fieldItem.FieldId == orderedFI.FieldId) {
                                        found = true;
                                        break;
                                    }
                                }

                                if (found == false) {
                                    sectionItem.Fields.splice(k, 1);
                                }
                            }
                        }

                        if (sectionItem.Fields.length > 0) {
                            groupHasChildren = true;
                        }
                        else {
                            groupItem.Sections.splice(j, 1);
                        }
                    }

                    if (groupItem.Sections.length == 0) {
                        groupItem.Sections = null;
                    }
                }

                if (groupHasChildren == false) {
                    this.CurrentFieldGroups().splice(i, 1);
                }
            }
        }
        else {
            for (var i = this.CurrentFieldGroups().length - 1; i > -1; i--) {
                var groupItem = this.CurrentFieldGroups()[i];
                var groupHasChildren = false;

                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var j = groupItem.Fields.length - 1; j > -1; j--) {
                        var fieldItem = groupItem.Fields[j];
                        if (fieldItem.IsUsed == true) {
                            groupItem.Fields.splice(j, 1);
                        }
                        else {
                            if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Tìm tên cột")) {

                                if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
                                    groupItem.Fields.splice(j, 1);
                                }
                            }
                        }
                    }

                    if (groupItem.Fields.length > 0) {
                        groupHasChildren = true;
                    }
                }

                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var j = groupItem.Sections.length - 1; j > -1; j--) {
                        var sectionItem = groupItem.Sections[j];
                        for (var k = sectionItem.Fields.length - 1; k > -1; k--) {
                            var fieldItem = sectionItem.Fields[k];

                            if (fieldItem.IsUsed == true) {
                                sectionItem.Fields.splice(k, 1);
                            }
                            else {
                                if ((this.SearchFieldText() != "") && (this.SearchFieldText() != "Tìm tên cột")) {
                                    if (fieldItem.FieldName.toLowerCase().indexOf(this.SearchFieldText().toLowerCase()) == -1) {
                                        sectionItem.Fields.splice(k, 1);
                                    }
                                }
                            }
                        }

                        if (sectionItem.Fields.length > 0) {
                            groupHasChildren = true;
                        }
                        else {
                            groupItem.Sections.splice(j, 1);
                        }
                    }

                    if (groupItem.Sections.length == 0) {
                        groupItem.Sections = null;
                    }
                }

                if (groupHasChildren == false) {
                    this.CurrentFieldGroups().splice(i, 1);
                }
            }
        }
    }

    this.ViewAllFields = function () {
        this.FilterMode("All");
        this.SearchFieldText("");
        this.UpdateView();
        this.SearchFieldText("Tìm tên cột");
    };

    this.EnterHandler = function (MappingModel, event) {
        if (event.keyCode == 13) {
            this.SearchFieldText($('#searchKeywordstep2').val());
            if ((this.SearchFieldText() != "Tìm tên cột") || (this.FilterMode() != "DataType")) {
                this.FilterMode("DataType");
                this.UpdateView();
            }
        }
        return true;
    }

    this.SearchFields = function () {
        if ((this.SearchFieldText() != "Tìm tên cột") || (this.FilterMode() != "DataType")) {
            this.FilterMode("DataType");
            this.UpdateView();
        }
        if (this.SearchFieldText() == "") {
            this.SearchFieldText("Tìm tên cột");
        }
    };

    this.GoBackHelp = function () {
        UploadFileModel.DisplayFirstView(false);
        HelpModel.DisplayHelp(true);
        MappingModel.DisplaySecondView(false);
        ReviewImportModel.DisplayThirdView(false);
    };

    this.MatchColumn = function (fieldId, fieldName) {
        if ((fieldId == null) || (fieldId == 0)) return;
        if (this.ActiveColumn == null) return;

        // Update the column mappings
        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];
            // Update the current column
            if (columnItem.ColumnName == this.ActiveColumn.ColumnName) {
                columnItem.MappedField = {
                    FieldId: fieldId,
                    FieldName: fieldName
                };
            }

            // update all possible fields of all columns to mark the dropped field as IsUsed
            var found = false;
            for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
                var groupItem = columnItem.PossibleGroups[j];
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var k = 0; k < groupItem.Fields.length; k++) {
                        var fieldItem = groupItem.Fields[k];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = true;
                            found = true;
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var k = 0; k < groupItem.Sections.length; k++) {
                        var sectionItem = groupItem.Sections[k];
                        for (var h = 0; h < sectionItem.Fields.length; h++) {
                            var fieldItem = sectionItem.Fields[h];
                            if (fieldItem.FieldId == fieldId) {
                                fieldItem.IsUsed = true;
                                found = true;
                                break;
                            }
                        }
                        if (found == true) {
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
            }
            for (var j = 0; j < columnItem.PossibleFieldsInOrder.length; j++) {
                var fieldItem = columnItem.PossibleFieldsInOrder[j];
                if (fieldItem.FieldId == fieldId) {
                    fieldItem.IsUsed = true;
                    break;
                }
            }
        }

        // Update the all fields to mark the dropped field as IsUsed
        var found1 = false;
        for (var j = 0; j < this.AllFieldGroups().length; j++) {
            var groupItem = this.AllFieldGroups()[j];
            if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                for (var k = 0; k < groupItem.Fields.length; k++) {
                    var fieldItem = groupItem.Fields[k];
                    if (fieldItem.FieldId == fieldId) {
                        fieldItem.IsUsed = true;
                        found1 = true;
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
            if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                for (var k = 0; k < groupItem.Sections.length; k++) {
                    var sectionItem = groupItem.Sections[k];
                    for (var h = 0; h < sectionItem.Fields.length; h++) {
                        var fieldItem = sectionItem.Fields[h];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = true;
                            found1 = true;
                            break;
                        }
                    }
                    if (found1 == true) {
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
        }

    };

    this.x_OutColumn = function (data) {
        MappingModel.UnMatchColumn(data.ColumnName, true);
        MappingModel.UpdateView();

    };

    this.UnMatchColumn = function (columnName, ignore) {

        // Update the column mappings
        var fieldId = 0;
        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];
            // Update the current column
            if (columnItem.ColumnName == columnName) {
                if ((typeof (columnItem.MappedField) != "undefined") && (columnItem.MappedField != null)) {
                    fieldId = columnItem.MappedField.FieldId;
                    columnItem.MappedField = null;
                }
                columnItem.IsIgnored = (ignore == true) ? true : false;

                break;
            }
        }

        if (fieldId == 0) return;

        for (var i = 0; i < this.MappingColumns().length; i++) {
            var columnItem = this.MappingColumns()[i];

            // update all possible fields of all columns to mark the undropped field as IsUnUsed
            var found = false;
            for (var j = 0; j < columnItem.PossibleGroups.length; j++) {
                var groupItem = columnItem.PossibleGroups[j];
                if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                    for (var k = 0; k < groupItem.Fields.length; k++) {
                        var fieldItem = groupItem.Fields[k];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = false;
                            found = true;
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
                if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                    for (var k = 0; k < groupItem.Sections.length; k++) {
                        var sectionItem = groupItem.Sections[k];
                        for (var h = 0; h < sectionItem.Fields.length; h++) {
                            var fieldItem = sectionItem.Fields[h];
                            if (fieldItem.FieldId == fieldId) {
                                fieldItem.IsUsed = false;
                                found = true;
                                break;
                            }
                        }
                        if (found == true) {
                            break;
                        }
                    }
                }
                if (found == true) {
                    break;
                }
            }
            for (var j = 0; j < columnItem.PossibleFieldsInOrder.length; j++) {
                var fieldItem = columnItem.PossibleFieldsInOrder[j];
                if (fieldItem.FieldId == fieldId) {
                    fieldItem.IsUsed = false;
                    break;
                }
            }

        }

        // Update the all fields to mark the dropped field as IsUnUsed
        var found1 = false;
        for (var j = 0; j < this.AllFieldGroups().length; j++) {
            var groupItem = this.AllFieldGroups()[j];
            if ((typeof (groupItem.Fields) != "undefined") && (groupItem.Fields != null)) {
                for (var k = 0; k < groupItem.Fields.length; k++) {
                    var fieldItem = groupItem.Fields[k];
                    if (fieldItem.FieldId == fieldId) {
                        fieldItem.IsUsed = false;
                        found1 = true;
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
            if ((typeof (groupItem.Sections) != "undefined") && (groupItem.Sections != null)) {
                for (var k = 0; k < groupItem.Sections.length; k++) {
                    var sectionItem = groupItem.Sections[k];
                    for (var h = 0; h < sectionItem.Fields.length; h++) {
                        var fieldItem = sectionItem.Fields[h];
                        if (fieldItem.FieldId == fieldId) {
                            fieldItem.IsUsed = false;
                            found1 = true;
                            break;
                        }
                    }
                    if (found1 == true) {
                        break;
                    }
                }
            }
            if (found1 == true) {
                break;
            }
        }

    };
    this.GoToDataCorrection = function () {
        if (this.AllColumnsMapped() == false) return;
        var ManualImportId = $('#StoreManualID').val();
        var mappingItems = [];

        for (var i = 0; i < this.MappingColumns().length; i++) {
            var mappingItem = this.MappingColumns()[i];
            var newItem = {
                ColumnName: mappingItem.ColumnName,
                IsIgnored: mappingItem.IsIgnored,
                MappedField: mappingItem.MappedField,
                PossibleGroups: null,
                PossibleFieldsInOrder: null
            };
            mappingItems.push(newItem);
        }
        init_review_import();
        hscroll_size(); //to set width

        var dataPost = { "file": ManualImportId, "MappingSettings": mappingItems };
        $.ajax({
            async: true,
            type: "POST",
            url: "/LeadImport/GetAllDataMapping",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            data: JSON.stringify(dataPost),
            success: function (dataErrors, textStatus, jqXHR) {
                $.fancybox.close();
                $('#DoNotImportLeadswithErrors').removeAttr("jcf-hidden");
                $('#DoNotImportLeadswithErrors').attr("class", "jcf-select");

                if (dataErrors.IsError == true) {
                    showCustomError(dataErrors.ErrorMessage);
                }
                else {
                    //Update IsIgnored in CellModel
                    var _ErrorRows = dataErrors.DataError.ErrorRows;
                    var _ColumnHeaders = dataErrors.DataError.ColumnHeaders;
                    var countErrorRows = _ErrorRows.length;
                    var countColumnHeaders = _ColumnHeaders.length;
                    if (countColumnHeaders > 0) {
                        for (var i = 0; i < countColumnHeaders; i++) {
                            if (countErrorRows > 0) {
                                for (var j = 0; j < countErrorRows; j++) {
                                    if (_ColumnHeaders[i].IsIgnored) {
                                        _ErrorRows[j].Cells[i].IsIgnored = true;
                                    }
                                    _ErrorRows[j].Cells[i].Type = _ColumnHeaders[i].Type;
                                    _ErrorRows[j].Cells[i].CellID = i + '-' + j;
                                    _ErrorRows[j].Cells[i].IsDone = false;

                                    //set class for cell
                                    if (_ErrorRows[j].Cells[i].IsDone) {
                                        _ErrorRows[j].Cells[i].ClassName = "col1 done";
                                    }
                                    else if (_ErrorRows[j].Cells[i].IsError)
                                    {
                                        if (_ErrorRows[j].Cells[i].Type == 64) {
                                            _ErrorRows[j].Cells[i].ClassName = "col1 error " + i + "ignoreall";
                                        }
                                        else {
                                            _ErrorRows[j].Cells[i].ClassName = "col1 error";
                                        }
                                    }
                                    else {
                                        _ErrorRows[j].Cells[i].ClassName = "col1";
                                    }
                                }
                            }
                        }
                    }
                    if (countErrorRows > 0) {
                        var displayError = false;
                        for (var i = 0; i < _ErrorRows[0].Cells.length; i++) {
                            if (!_ErrorRows[0].Cells[i].IsIgnored) {
                                if ((_ErrorRows[0].Cells[i].IsError == true) || (_ErrorRows[0].Cells[i].Value == "")) {
                                    displayError = true;
                                    break;
                                }
                            }
                        }
                        ReviewImportModel.HasErrorsToDisplay(displayError);
                    }
                    else {
                        ReviewImportModel.HasErrorsToDisplay(false);
                    }

                    UploadFileModel.DisplayFirstView(false);
                    HelpModel.DisplayHelp(false);
                    MappingModel.DisplaySecondView(false);
                    ReviewImportModel.DisplayThirdView(true);
                    hscroll_size(); // to set width

                    ReviewImportModel.ColumnHeaders(dataErrors.DataError.ColumnHeaders);
                    
                    ReviewImportModel.ErrorRows(_ErrorRows);
                }
            },
            error: function (xhr, status, error) {
                $.fancybox.close();
                showCustomError(eval("(" + xhr.responseText + ")"));
            }
        });
    };
};